package com.fzg.web;

import com.fzg.entity.Comment;
import com.fzg.entity.User;
import com.fzg.service.BlogService;
import com.fzg.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.Random;

/**
 * create by fzg
 * 2021/11/27 9:12
 */

@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;

    @Value("${comment.avatar}")
    private  String avatar;

    @Value("${comment.avatar1}")
    private  String avatar1;

    @Value("${comment.avatar2}")
    private  String avatar2;

    @Value("${comment.avatar3}")
    private  String avatar3;

    @Value("${comment.avatar4}")
    private  String avatar4;

    @Value("${comment.avatar5}")
    private  String avatar5;

    @Value("${comment.avatar6}")
    private  String avatar6;

    @Value("${comment.avatar7}")
    private  String avatar7;

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model){
        model.addAttribute("comments",commentService.listCommentByBlogId(blogId));
        return "blog :: commentList";
    }

    @PostMapping("/comments")
    public String post(Comment comment, HttpSession session){
        Long blogId = comment.getBlog().getId();
        comment.setBlog(blogService.getBlog(blogId));
        User user = (User) session.getAttribute("user");
        if (user != null){
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        }else {
            // 随机取一个
            Random r = new Random();
            int i = r.nextInt(8);
            if (i == 0){
                comment.setAvatar(avatar);
            }else if (i == 1){
                comment.setAvatar(avatar1);
            }else if (i == 2){
                comment.setAvatar(avatar2);
            }else if (i == 3){
                comment.setAvatar(avatar3);
            }else if (i == 4){
                comment.setAvatar(avatar4);
            }else if (i == 5){
                comment.setAvatar(avatar5);
            }else if (i == 6){
                comment.setAvatar(avatar6);
            }else {
                comment.setAvatar(avatar7);
            }
            comment.setAdminComment(false);
        }
        commentService.saveComment(comment);

        return "redirect:/comments/" + comment.getBlog().getId();
    }


}
